package cn.topkinson.lagou.s3m4.user.controller;

import cn.topkinson.lagou.s3m4.user.service.UserService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author huangzihao
 * @Date 2020/9/9 15:40
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 注册接⼝，true成功，false失败
     * @param email
     * @param password
     * @param code
     * @return
     */
    @GetMapping(value = "/register/{email}/{password}/{code}",produces =  { "application/json;charset=UTF-8"})
    public String register(@PathVariable String email, @PathVariable String password, @PathVariable String code){
        Map<String,Object> map = new HashMap<>();
        map.put("isOk",userService.register(email,password,code));
        return JSON.toJSONString(map);
    }

    /**
     * 是否已注册，根据邮箱判断,true代表已经注册过，
     * false代表尚未注册
     * @param email
     * @return
     */
    @GetMapping(value = "/isRegistered/{email}",produces =  { "application/json;charset=UTF-8"})
    public Boolean isRegistered(@PathVariable String email){
        return userService.isRegistered(email);
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和
     * 密码⽣成token，token存⼊数据库，并写⼊cookie
     * 中，登录成功返回邮箱地址，重定向到欢迎⻚
     * @param email
     * @param password
     * @return
     */
    @GetMapping(value = "/login/{email}/{password}",produces = { "application/json;charset=UTF-8"})
    public String login(@PathVariable String email,@PathVariable String password){
        Map<String,Object> map = new HashMap<>();
        map.put("token",userService.login(email,password));
        return JSON.toJSONString(map);
    }

    /**
     * 根据token查询⽤户登录邮箱接⼝
     * @param token
     * @return
     */
    @GetMapping(value = "info/{token}",produces =  { "application/json;charset=UTF-8"})
    public String info(@PathVariable String token){
        Map<String,Object> map = new HashMap<>();
        map.put("email",userService.info(token));
        return JSON.toJSONString(map);
    }
}
